import { Box, Grid, Heading, Text, HStack, Button, Center, Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton, FormControl, FormLabel, Input, useDisclosure, VStack } from '@chakra-ui/react';
import { useState, useEffect } from 'react';
import CredentialCard, { Credential } from 'components/modules/CredentialCard/CredentialCard';
import request from 'utils/request';

// 生成示例凭证数据
const generateMockCredentials = (): Credential[] => {
  const credentials: Credential[] = [
    {
      id: '0x7d5f3e52f4f7e1b7f9c4e9d8a1b2c3d4e5f6a7b8',
      attributes: [
        { key: '学历', value: '研究生' },
        { key: '专业', value: '计算机科学' },
        { key: '学校', value: '清华大学' },
        { key: '毕业年份', value: '2023' }
      ],
      issuer: '教育部学位认证中心',
      issuerId: '0x8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b',
      issuedDate: '2023-06-30'
    },
    {
      id: '0x9e8f7c6d5e4f3a2b1c0d9e8f7c6d5e4f3a2b1c0d',
      attributes: [
        { key: '证书类型', value: 'AWS认证解决方案架构师' },
        { key: '等级', value: '专家级' },
        { key: '有效期', value: '2025-12-31' }
      ],
      issuer: 'Amazon Web Services',
      issuerId: '0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1',
      issuedDate: '2023-01-15'
    },
    {
      id: '0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b',
      attributes: [
        { key: '职位', value: '高级工程师' },
        { key: '工作年限', value: '5年' },
        { key: '技能领域', value: '区块链开发' }
      ],
      issuer: '某知名科技公司',
      issuerId: '0x3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2',
      issuedDate: '2023-03-20'
    },
    {
      id: '0x4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3',
      attributes: [
        { key: '语言等级', value: '托福' },
        { key: '分数', value: '108' },
        { key: '有效期', value: '2024-12-31' }
      ],
      issuer: 'ETS',
      issuerId: '0x5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4',
      issuedDate: '2022-12-15'
    },
    {
      id: '0x6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5',
      attributes: [
        { key: '证书类型', value: 'PMP项目管理认证' },
        { key: '认证编号', value: 'PMP-2023-12345' },
        { key: '状态', value: '有效' }
      ],
      issuer: 'Project Institute',
      issuerId: '0x7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6',
      issuedDate: '2023-05-20'
    },
    {
      id: '0x8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7',
      attributes: [
        { key: '认证类型', value: 'ISO 27001审核员' },
        { key: '级别', value: '主任审核员' },
        { key: '专业领域', value: '信息安全管理' }
      ],
      issuer: 'International Organization',
      issuerId: '0x9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8',
      issuedDate: '2023-04-10'
    },
    {
      id: '0x8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b8',
      attributes: [
        { key: '认证类型', value: 'CISSP信息安全认证' },
        { key: '状态', value: '有效' },
        { key: '认证时间', value: '2023年' }
      ],
      issuer: 'ISC²',
      issuerId: '0x9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c9',
      issuedDate: '2023-07-15'
    }
  ];
  return credentials;
};

const NFTBalances = () => {
  const [credentials, setCredentials] = useState<Credential[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [applicantId, setApplicantId] = useState('');
  const [issuerId, setIssuerId] = useState('');
  const { isOpen, onOpen, onClose } = useDisclosure();
  const itemsPerPage = 6;

  useEffect(() => {
    const mockCredentials = generateMockCredentials();
    setCredentials(mockCredentials);
    // 从 localStorage 获取申请者 ID
    const storedId = localStorage.getItem('user_login_hash');
    if (storedId) {
      setApplicantId(storedId);
    }
    request.get('home/credentials')
  }, []);

  // 计算总页数
  const totalPages = Math.ceil(credentials.length / itemsPerPage);

  // 获取当前页的凭证
  const getCurrentPageCredentials = () => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return credentials.slice(startIndex, endIndex);
  };

  // 页面切换处理
  const handlePageChange = (pageNumber: number) => {
    setCurrentPage(pageNumber);
  };

  const onPanelClose = () => {
    setIssuerId('');
    onClose();
  };

  const handleSubmit = async () => {
    // 这里处理提交逻辑
    console.log('提交申请:', {
      applicantId,
      issuerId
    });
    request.get('credential/apply')
    setIssuerId(''); 
    onClose();
  };

  return (
    <>
      <HStack justify="space-between" marginBottom={6}>
        <Heading size="lg">我的凭证</Heading>
        <Button colorScheme="blue" onClick={onOpen}>
          申请凭证
        </Button>
      </HStack>

      {/* 申请凭证弹窗 */}
      <Modal isOpen={isOpen} onClose={onClose}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>申请凭证</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <VStack spacing={4}>
              <FormControl>
                <FormLabel>申请者 ID</FormLabel>
                <Input 
                  value={applicantId} 
                  isReadOnly 
                  bg="gray.100"
                  color="gray.700"
                  _hover={{ bg: 'gray.100' }}
                  _focus={{ 
                    bg: 'gray.100',
                    borderColor: 'gray.300',
                    color: 'gray.700'
                  }}
                  _selection={{
                    background: 'blue.100',
                    color: 'gray.900'
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>发行方 ID</FormLabel>
                <Input 
                  value={issuerId}
                  onChange={(e) => setIssuerId(e.target.value)}
                  placeholder="请输入发行方ID"
                />
              </FormControl>
            </VStack>
          </ModalBody>

          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={onPanelClose}>
              取消
            </Button>
            <Button 
              colorScheme="blue" 
              onClick={handleSubmit}
              isDisabled={!issuerId.trim()}
            >
              提交申请
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>

      {credentials.length ? (
        <Box>
          <Grid templateColumns="repeat(3, 1fr)" gap={6} mb={6}>
            {getCurrentPageCredentials().map((credential, index) => (
              <CredentialCard key={index} credential={credential} />
            ))}
          </Grid>
          
          {totalPages > 1 && (
            <Center mt={6}>
              <HStack spacing={2}>
                <Button
                  size="sm"
                  onClick={() => handlePageChange(currentPage - 1)}
                  isDisabled={currentPage === 1}
                  colorScheme="blue"
                >
                  上一页
                </Button>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNum) => (
                  <Button
                    key={pageNum}
                    size="sm"
                    onClick={() => handlePageChange(pageNum)}
                    colorScheme={currentPage === pageNum ? "blue" : "gray"}
                    variant={currentPage === pageNum ? "solid" : "outline"}
                  >
                    {pageNum}
                  </Button>
                ))}
                <Button
                  size="sm"
                  onClick={() => handlePageChange(currentPage + 1)}
                  isDisabled={currentPage === totalPages}
                  colorScheme="blue"
                >
                  下一页
                </Button>
              </HStack>
            </Center>
          )}
        </Box>
      ) : (
        <Box textAlign="center" py={10}>
          <Text>您还没有任何凭证</Text>
        </Box>
      )}
    </>
  );
};

export default NFTBalances;
